//
//  AppDelegate.m
//  MIDI
//
//  Created by 王禹丞 on 15/8/31.
//  Copyright (c) 2015年 QXSX. All rights reserved.
//

#import "AppDelegate.h"
#import "UMSocial.h"
#import "UMSocialWechatHandler.h"
#import "UIViewController+Create.h"
#import "MIDICertificationViewCtrler.h"
#import "MrMIDISearchViewCtrler.h"
#import "ChangeInforViewCtrl.h"
#import "ChangeLocationViewCtrler.h"
#import "GeTuiSdk.h"
#import "SIAlertView.h"
#import <AlipaySDK/AlipaySDK.h>
#import "MBProgressHUD+YC.h"
#import "QXNetWorkTool.h"
#import "UserDataSingleton.h"
#import "WXApi.h"
#import "APIAdress.h"
#import "AccountTool.h"
#import "AliPayTool.h"
#import "MyTestViewController.h"
#import "BuyMusicViewController.h"
#import "BuyMusicDetailViewViewController.h"
#import "UMSocial.h"
#import "UMSocialWechatHandler.h"
#import "MyOrderViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "YCAudioPlayer.h"
#import "TestResultViewController.h"


#define GTAppID @"i2VWxI7hztAapcGyHPmrM1"
#define GTAppSecret @"IZwCt6nZfu64zt97mttLW9"
#define GTAppKey @"YVKSMDtVZE9nhicEsBGhb8"
#define GTMasterSecret @"yoaWKXaX12AD2kVgjAKMw9"


@interface AppDelegate ()<GeTuiSdkDelegate, QXNetWorkToolDelegate, WXApiDelegate,UIAlertViewDelegate>

@property (copy,nonatomic)NSString * deviceToken;

@property (copy, nonatomic) NSString *clientId;

@property (copy, nonatomic) NSString *payloadId;

@property (assign, nonatomic) int lastPayloadIndex;

@property (strong, nonatomic) UINavigationController *nav;

@property (copy, nonatomic) NSString *flag;

@property (nonatomic,strong) NSDictionary * examDict;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.nav = [[UINavigationController alloc]initWithRootViewController:[self.window rootViewController]];
    //友盟分享
    [UMSocialData setAppKey:@"5644b5ab67e58ef4e4001caf"];
    
    //设置微信AppId、appSecret，分享url
    [UMSocialWechatHandler setWXAppId:@"wxee179977f8060101" appSecret:@"aabc6f5feec80e1d9249f7a0ce9d1cee" url:@"http://www.umeng.com/social"];
    
    self.window.rootViewController = self.nav;
    self.window.rootViewController.tabBarController.tabBar.tintColor = [UIColor whiteColor];
    
    
    UIApplication *app = [UIApplication sharedApplication];
    
    app.applicationIconBadgeNumber = 0;
    
//    [UMSocialData setAppKey:UmengAppkey];
//    
//    [UMSocialWechatHandler setWXAppId:AppID appSecret:AppSecret url:nil];
    
//    [UMSocialWechatHandler setWXAppId:AppID appSecret:AppSecret url:(NSString *)url;
    
    //
    // [1]:使用APPID/APPKEY/APPSECRENT创建个推实例
    
    
    [self startSdkWith:GTAppID appKey:GTAppKey appSecret:GTAppSecret];
    
    // [2]:注册APNS
    
    [self registerRemoteNotification];
    
    // [2-EXT]: 获取启动时收到的APN数据
    
    NSDictionary*message=[launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    
    if (message) {
        
        NSString*payloadMsg = [message objectForKey:@"payload"];
        
        NSString*record = [NSString stringWithFormat:@"[APN]%@,%@",[NSDate date],payloadMsg];
        
        //[_vc logMsg:record];
        
    }
    
    
    NSError* error;
   
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
    
    //向微信注册
    [WXApi registerApp:WXPayAppID withDescription:@"demo 2.0"];
    
    return YES;
}



- (void)applicationWillResignActive:(UIApplication *)application {
    
    
    if ([YCAudioPlayer sharedYCAudioPlayer].player.state == STKAudioPlayerStatePlaying||[YCAudioPlayer sharedYCAudioPlayer].player.state == STKAudioPlayerStateBuffering||[YCAudioPlayer sharedYCAudioPlayer].player.state == STKAudioPlayerStatePaused ||[YCAudioPlayer sharedYCAudioPlayer].player.state == STKAudioPlayerStateStopped) {
        //有音乐播放时，才给后台权限，不做流氓应用。
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
        [self becomeFirstResponder];
        //开启定时器
//        [[MBAudioPlayer shareInstance] decideTimerWithType:MBAudioTimerStartBackground andBeginState:YES];
//        [[MBAudioPlayer shareInstance] configNowPlayingInfoCenter];

        [[YCAudioPlayer sharedYCAudioPlayer].player resume];
    
    }
    else
    {
        [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
        [self resignFirstResponder];
        //检测是都关闭定时器
//        [[MBAudioPlayer shareInstance] decideTimerWithType:MBAudioTimerStartBackground andBeginState:NO];
    }
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
      [GeTuiSdk enterBackground];
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}



# pragma mark 个推 push


- (void)startSdkWith:(NSString *)appID appKey:(NSString *)appKey appSecret:(NSString *)appSecret
{
    
    
    NSError *err = nil;
    
    //[1-1]:通过 AppId、 appKey 、appSecret 启动SDK
    [GeTuiSdk startSdkWithAppId:appID appKey:appKey appSecret:appSecret delegate:self error:&err];
    
    //[1-2]:设置是否后台运行开关
    [GeTuiSdk runBackgroundEnable:YES];
    //[1-3]:设置电子围栏功能，开启LBS定位服务 和 是否允许SDK 弹出用户定位请求
    [GeTuiSdk lbsLocationEnable:YES andUserVerify:YES];
    
    if (err) {
        
        // [_vc logMsg:[NSString stringWithFormat:@"%@", [err localizedDescription]]];
    }
}


-(void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken

{
    
    NSString *token = [[deviceToken description]
                       stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    
    //  [_deviceToken release];
    
    _deviceToken = [token stringByReplacingOccurrencesOfString:@" " withString:@""] ;
    
    NSLog(@"deviceToken:%@",_deviceToken);
    
    // [3]:向个推服务器注册deviceToken
    
    [GeTuiSdk registerDeviceToken:_deviceToken];
    
}


-(void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error

{
    
    // [3-EXT]:如果APNS注册失败，通知个推服务器
    
    [GeTuiSdk registerDeviceToken:@""];
    
}


-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    [GeTuiSdk resume];  // 恢复个推SDK运行
    
    
    completionHandler(UIBackgroundFetchResultNewData);
    
}

NSString* const NotificationCategoryIdent  = @"ACTIONABLE";
NSString* const NotificationActionOneIdent = @"ACTION_ONE";
NSString* const NotificationActionTwoIdent = @"ACTION_TWO";

- (void)registerRemoteNotification {
    
#ifdef __IPHONE_8_0
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        //IOS8 新的通知机制category注册
        UIMutableUserNotificationAction *action1;
        action1 = [[UIMutableUserNotificationAction alloc] init];
        [action1 setActivationMode:UIUserNotificationActivationModeBackground];
        [action1 setTitle:@"取消"];
        [action1 setIdentifier:NotificationActionOneIdent];
        [action1 setDestructive:NO];
        [action1 setAuthenticationRequired:NO];
        
        UIMutableUserNotificationAction *action2;
        action2 = [[UIMutableUserNotificationAction alloc] init];
        [action2 setActivationMode:UIUserNotificationActivationModeBackground];
        [action2 setTitle:@"确定"];
        [action2 setIdentifier:NotificationActionTwoIdent];
        [action2 setDestructive:NO];
        [action2 setAuthenticationRequired:NO];
        
        UIMutableUserNotificationCategory *actionCategory;
        actionCategory = [[UIMutableUserNotificationCategory alloc] init];
        [actionCategory setIdentifier:NotificationCategoryIdent];
        [actionCategory setActions:@[action1, action2]
                        forContext:UIUserNotificationActionContextDefault];
        
        NSSet *categories = [NSSet setWithObject:actionCategory];
        UIUserNotificationType types = (UIUserNotificationTypeAlert|
                                        UIUserNotificationTypeSound|
                                        UIUserNotificationTypeBadge);
        
        UIUserNotificationSettings *settings;
        settings = [UIUserNotificationSettings settingsForTypes:types categories:categories];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        
        
    } else {
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|
                                                                       UIRemoteNotificationTypeSound|
                                                                       UIRemoteNotificationTypeBadge);
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
    }
#else
    UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|
                                                                   UIRemoteNotificationTypeSound|
                                                                   UIRemoteNotificationTypeBadge);
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
#endif
    
}


- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId  // SDK 返回clientid

{
    
    // [4-EXT-1]: 个推SDK已注册，返回clientId
    
    _clientId = clientId;
    
    [[UserDataSingleton shareInstance] setGeTuiClientID:_clientId];
    
    if (_deviceToken) {
        
        [GeTuiSdk registerDeviceToken:_deviceToken];
    }
}


-(void)GeTuiSdkDidReceivePayload:(NSString*)payloadId andTaskId:(NSString*)taskId andMessageId:(NSString *)aMsgId fromApplication:(NSString *)appId

{
    
    // [4]: 收到个推消息
    
    _payloadId = payloadId;
    
    NSData *payload = [GeTuiSdk retrivePayloadById:payloadId]; //根据payloadId取回Payload
    
    NSString *payloadMsg = nil;
    
//    if (payload) {
//        
//        payloadMsg = [[NSString alloc] initWithBytes:payload.bytes
//                      
//                                              length:payload.length
//                      
//                                            encoding:NSUTF8StringEncoding];
//        
//    }
//    

     _examDict= [NSJSONSerialization JSONObjectWithData:payload options:NSJSONReadingMutableLeaves error:nil];
    
    if ([_examDict[@"type"] isEqualToString:@"0"]) {
        
        UIAlertView *altView = [[UIAlertView alloc]initWithTitle:@"迷笛" message:_examDict[@"message"] delegate:self cancelButtonTitle:@"确定"otherButtonTitles:nil];
        
        [altView show];
        
    }else{
    
        UIAlertView *altView = [[UIAlertView alloc]initWithTitle:@"迷笛" message:_examDict[@"message"] delegate:self cancelButtonTitle:@"取消"otherButtonTitles:@"确定",nil];
        
        altView.tag = 10086;
        
        [altView show];
    
    }
    
    
//      
//    NSString *record = [NSString stringWithFormat:@"%d, %@, %@",++_lastPayloadIndex, [self formateTime:[NSDate date]], payloadMsg];
//    
//    NSLog(@"task id : %@, messageId:%@", taskId, aMsgId);
    
    
    
}

-(NSString*) formateTime:(NSDate*) date {
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:@"HH:mm:ss"];
    
    NSString* dateTime = [formatter stringFromDate:date];
    
    return dateTime;
}


- (void)GeTuiSdkDidSendMessage:(NSString *)messageId result:(int)result {
    
    // [4-EXT]:发送上行消息结果反馈
    
    NSString *record = [NSString stringWithFormat:@"Received sendmessage:%@ result:%d", messageId, result];
    
    //  [_viewController logMsg:record];
    
    
}


- (void)GeTuiSdkDidOccurError:(NSError *)error

{
    
    // [EXT]:个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
    
    //    [_viewController logMsg:[NSString
    //                             stringWithFormat:@">>>[GexinSdk error]:%@", [error localizedDescription]]];
    
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [WXApi handleOpenURL:url delegate:self];
}

//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
//{
//    return  [WXApi handleOpenURL:url delegate:self];
//}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    if ([sourceApplication isEqualToString:@"com.tencent.xin"])
        return  [WXApi handleOpenURL:url delegate:self];
    else
    {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            
            [AliPayTool processResult:resultDic Target:self];
            
//            NSString *flag = @"";
//            
//            if ([resultDic[@"resultStatus"] isEqualToString:@"9000"] ) {
//                
//                [MBProgressHUD showSuccess:@"支付成功"];
//                flag = @"1";
//                
//            }else{
//                
//                [MBProgressHUD showSuccess:@"支付失败"];
//                flag = @"0";
//            }
//            
//            [MBProgressHUD showMessage:@"正在加载" toView:nil];
//            
//            QXNetWorkTool *netTools = [[QXNetWorkTool alloc]init];
//            netTools.QXNetWorkDelegate = self;
//            
//            NSString *payItem = [AccountTool takePayItem];
//            
//            if ([payItem isEqualToString:VPayBuyMusic])
//            {
//                //记录购买结果
//                [netTools GetDataFromServerWithPostMethodandInterfaceName:MyOrderBuyRecorderInterface andParameter:
//                 @[@{
//                       @"order_id":[AccountTool takeOrderId],
//                       @"flag":flag
//                       }] tag:1];
//            }
//            else if ([payItem isEqualToString:VPaySignCost])
//            {
//                //支付报名费付款
//                [netTools GetDataFromServerWithPostMethodandInterfaceName:PaySiginUpCostInterface andParameter:
//                 @[@{@"exam_id": [AccountTool takeExamId],
//                     @"flag":flag}] tag:2];
//            }
//            else if ([payItem isEqualToString:VPayCerficationCost])
//            {
//                //支付证书工本费
//                [netTools GetDataFromServerWithPostMethodandInterfaceName:PayCertificateCostInterface andParameter:
//                 @[@{@"exam_id":[AccountTool takeExamId],
//                     @"status":flag,                                          @"courier_cost":[AccountTool takeOrderPrice]}] tag:3];
//            }
        }];
        
        return YES;
        
        //    return  [UMSocialSnsService handleOpenURL:url];
    }
    
    return YES;
}

-(void) onResp:(BaseResp*)resp
{
    NSString *strMsg = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
    NSString *strTitle;
    
    if([resp isKindOfClass:[PayResp class]]){
        
        //支付返回结果，实际支付结果需要去微信服务器端查询
        strTitle = [NSString stringWithFormat:@"支付结果"];
        
        self.flag = @"";
        
        switch (resp.errCode) {
            case WXSuccess:
            {
                [MBProgressHUD showSuccess:@"支付成功！"];
                self.flag = @"1";
                break;
            }
                
            default:
            {
                [MBProgressHUD showError:@"支付失败！"];
                self.flag = @"0";
                break;
            }
        }
        
//        [MBProgressHUD showMessage:@"正在加载"];
        
        QXNetWorkTool *netTools = [[QXNetWorkTool alloc]init];
        netTools.QXNetWorkDelegate = self;
        
        NSString *payItem = [AccountTool takePayItem];
        
        if ([payItem isEqualToString:VPayBuyMusic])
        {
            //记录购买结果
            [netTools GetDataFromServerWithPostMethodandInterfaceName:MyOrderBuyRecorderInterface andParameter:
             @[@{
                   @"order_id":[AccountTool takeOrderId],
                   @"flag":self.flag
                   }] tag:6666];
            
            if ([self.flag isEqualToString:@"1"])
            {
            }
        }
        else if ([payItem isEqualToString:VPaySignCost])
        {
            //支付报名费
            [netTools GetDataFromServerWithPostMethodandInterfaceName:PaySiginUpCostInterface andParameter:
             @[@{@"exam_id": [AccountTool takeExamId],
                 @"flag":self.flag}] tag:7777];
            
        }
        else if ([payItem isEqualToString:VPayCerficationCost])
        {
            //支付证书工本费
            [netTools GetDataFromServerWithPostMethodandInterfaceName:PayCertificateCostInterface andParameter:
             @[@{@"exam_id":[AccountTool takeExamId],
                 @"status":self.flag,                                          @"courier_cost":[AccountTool takeOrderPrice]}] tag:8888];
        }
    }
}

#pragma    ---QuxNetTool
-(void)GetSuccessResponse:(id)Response andTag:(int)tag
{
//    [MBProgressHUD hideHUD];
}

-(void)GetFailResponse:(id)Response andTag:(int)tag
{
//    [MBProgressHUD hideHUD];
}

-(void)GetSuccessMessage:(id)message andTag:(int)tag
{
    switch (tag)
    {
        case 6666:
        {
            if ([self.flag isEqualToString:@"1"])
            {
                if ([[AccountTool takePayMusicPopToView] isEqualToString:VPayBuyMusicPopToBuyMusicView])
                {
                    for (UIViewController *controller in self.nav.viewControllers)
                    {
                        if ([controller isKindOfClass:[BuyMusicViewController class]])
                        {
                            UIAlertView * alertView = [[UIAlertView alloc]
                               initWithTitle:@"支付成功"
                               message:nil
                               delegate:(BuyMusicViewController*)controller
                               cancelButtonTitle:@"取消"
                               otherButtonTitles:@"查看",nil];
                            
                            alertView.tag = 444;
                            [alertView show];
                            break;
                        }
                    }
                }
                else if ([[AccountTool takePayMusicPopToView] isEqualToString:VPayBuyMusicPopToMyOrderView])
                {
                    for (UIViewController *controller in self.nav.viewControllers)
                    {
                        if ([controller isKindOfClass:[MyOrderViewController class]])
                        {
                            UIAlertView * alertView = [[UIAlertView alloc]
                                                       initWithTitle:@"支付成功"
                                                       message:nil
                                                       delegate:(MyOrderViewController*)controller
                                                       cancelButtonTitle:@"取消"
                                                       otherButtonTitles:@"查看",nil];
                            
                            alertView.tag = 444;
                            [alertView show];
                            
                            MyOrderViewController* con = (MyOrderViewController*)controller;
                             [con refreshOrderNotPayList];
                            
                            break;
                        }
                    }
                }
                else if ([[AccountTool takePayMusicPopToView] isEqualToString:VPayBuyMusicPopToNone])
                {
                    for (UIViewController *controller in self.nav.viewControllers)
                    {
                        if ([controller isKindOfClass:[BuyMusicDetailViewViewController class]])
                        {
                            UIAlertView * alertView = [[UIAlertView alloc]
                                                       initWithTitle:@"支付成功"
                                                       message:nil
                                                       delegate:(BuyMusicDetailViewViewController*)controller
                                                       cancelButtonTitle:@"取消"
                                                       otherButtonTitles:@"查看",nil];
                            
                            alertView.tag = 444;
                            [alertView show];
                            
                            BuyMusicDetailViewViewController* buyMusicView = (BuyMusicDetailViewViewController*)controller;
                            buyMusicView.buy = @"1";
                            
                            [buyMusicView refreshPage];
                            
                            break;
                        }
                    }
                }
            }
            
            break;
        }
        case 7777:
        {
            if ([self.flag isEqualToString:@"1"])
            {
                for (UIViewController *controller in self.nav.viewControllers)
                {
                    if ([controller isKindOfClass:[MyTestViewController class]])
                    {
                        [self.nav popToViewController:controller animated:YES];
                    }
                }
            }
            break;
        }
        case 8888:
        {
            //支付工本费
            if ([self.flag isEqualToString:@"1"])
            {
                for (UIViewController *controller in self.nav.viewControllers)
                {
//                    if ([controller isKindOfClass:[MyTestViewController class]])
//                    {
//                        [self.nav popToViewController:controller animated:YES];
//                    }
                    
                    if ([controller isKindOfClass:[TestResultViewController class]])
                    {
                        TestResultViewController *ptr = (TestResultViewController *)controller;
                        if (ptr)
                        {
                            [ptr setShowreciveCertificateBtn];
                        }
                    }
                }
            }
            break;
        }
            
        case 10086:{
        
            [MBProgressHUD showSuccess:message];
        
        }
        
    }
}

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return UIInterfaceOrientationMaskPortrait;
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{


    if (alertView.tag == 10086) {
        
        QXNetWorkTool *netTools = [[QXNetWorkTool alloc]init];

        netTools.QXNetWorkDelegate = self;

        
        if (buttonIndex == 1) {
            
            [netTools GetDataFromServerWithPostMethodandInterfaceName:ExaminerAcceptInterface andParameter:
             @[@{
                   @"id":_examDict[@"id"],
                   @"state":@"10",
                   @"exam_id":_examDict[@"exam_id"]
                   }] tag:10086];
        }
        
        if (buttonIndex == 0) {
            
            [netTools GetDataFromServerWithPostMethodandInterfaceName:ExaminerAcceptInterface andParameter:
             @[@{
                   @"id":_examDict[@"id"],
                   @"state":@"11",
                   @"exam_id":_examDict[@"exam_id"]
                   }] tag:10086];
        }
        
        
    }
}


@end























